<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>axios的取消请求</title>
  </head>
  <link rel="stylesheet" href="./css/bootstrap.min.css">
  <style>
    body {
      margin: 0 auto;
    }

    .div {
      margin: 40px auto;
      width: 1000px;
    }
  </style>

  <body>
    <div class="div">
      <h2>axios的取消发送</h2>
      <hr>
      <button type="button" class="btn btn-primary">发送get请求</button>
      <button type="button" class="btn btn-danger">取消发送请求</button>
    </div>
  </body>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script>
    let btns = document.querySelectorAll(".btn");
    /*
    默认配置：
    */
    //  默认方法
    axios.defaults.method = "get";
    //  默认URL
    axios.defaults.baseURL = "http://localhost:3000";
    // 默认超时时长
    axios.defaults.timeout = 4000;
    // 默认参数
    axios.defaults.params = {
      id: 3000
    }
    //2.2.声明一个全局变量
    let cancel = null;
    // 1.发送get请求
    btns[0].addEventListener('click', function () {
      // 2.6 检测下上一次请求是否完成
      if (cancel != null) {
        cancel();
      }

      axios({
          url: "/posts",
          // 2.1.添加配置对象的属性
          cancelToken: new axios.CancelToken(function executor(c) {
            // An executor function receives a cancel function as a parameter
            // 3.将c赋值给cancel
            cancel = c;
          })
        }).then((resource) => {
          console.log(resource);
          // 2.5 将cancel复原
          cancel = null
        })
        .catch((error) => {
          console.log(error);
        })
    });

    //2.取消发送请求
    btns[1].onclick = function () {
      // 2.4.执行一下cancel函数
      cancel();
    }
  </script>

</html>